/*
 * $Header: $
 * $Id$
 *
 * Copyright (c) 2011, Mike DePhillips. All Rights Reserved.
 * This code may not be used without the express written permission
 * of the copyright holder, Mike DePhillips.
 */

package com.facebook.bannermaker.android.activity.makebanner;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import com.facbook.bannermaker.android.util.ActivityUtil;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.bannermaker.android.R;
import com.facebook.bannermaker.android.util.AppConstants;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

/**
 * Activity for browsing inbox and acquiring tasks
 *
 * @author Michael DePhillips
 * 
 */
public class MakeBannerMemActivity extends Activity {

	// Class Constants
    private static final String APP_ID = "212393005452204";
    private static final int IMAGE_PICK = 1234;
    
    // Member Variables
    public Facebook m_facebook = new Facebook(APP_ID);
    protected String m_id = null;
    protected String m_filePath = null;
    List<Bitmap> m_bitmaps = null;
    private boolean m_imageSet = false;
    private String m_name = null;
    protected boolean m_isPostingBanner = false;
    protected EditText m_urlInput = null;   
   
    // Google Tracker
    private GoogleAnalyticsTracker tracker;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.banner_maker_memory);  

        tracker = GoogleAnalyticsTracker.getInstance();

        // Start the tracker in manual dispatch mode...
        tracker.startNewSession(AppConstants.GOOGLE_ANALYTICS_CODE, this);
        
        // get the facebook id and file path to the image from the last activity
        Bundle bundle = getIntent().getExtras();
        if( bundle != null ) {
            m_id = bundle.getString(AppConstants.JSON_ME_ID);
            m_filePath = bundle.getString(AppConstants.IMAGE_FILEPATH);

            // set image if it is a valid image file
            ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);                
            if( image.setBitmap(MakeBannerMemActivity.this, m_filePath) ) {
                m_imageSet = true;
            }
            else {
                AlertDialog alert = ActivityUtil.getAlertOkFinishDialogue(this, "Not a supported image file");
                alert.show();
            }
        }
    }    

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // retrieve image from cursor
        if( requestCode == IMAGE_PICK ) {
            if(resultCode == RESULT_OK){  

                Uri selectedImageUri = data.getData();

                //OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                //MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                String filePath = null;
                //NOW WE HAVE OUR WANTED STRING
                if(selectedImagePath!=null) {
                    filePath = selectedImagePath;
                }
                else {
                    filePath = filemanagerstring;
                }    

                // set image if it is a valid image file
                ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);                
                if( image.setBitmap(MakeBannerMemActivity.this, filePath) ) {
                    m_imageSet = true;
                    m_filePath = filePath;
                }
                else {
                    AlertDialog alert = ActivityUtil.getAlertOkDialogue(MakeBannerMemActivity.this, "Not a supported image file");
                    alert.show();
                }
            }
            else {
                finish();
            }
        }
        else {
            finish();
        }
    }

    /**
     * Gets a file path from a cursor that is returned from gallery intent
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor!=null)
        {
            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else return null;
    }


    /**
     * Updates the text to the current cursor dimensions
     * @param image
     */
    public void updateCursorSizeValues(ScrollableImageView image) {        
        TextView cursorSizeText = (TextView)findViewById(R.id.text_cursor_size);
        String strWidth = new Integer(image.getCursorWidth()).toString();
        String strHeight = new Integer(image.getCursorHeight()).toString();
        cursorSizeText.setText( strWidth + " x " + strHeight );
    }

    /**
     * Increase the cursor size when button clicked
     * @param v
     */
    public void onIncreaseSizeClicked(View v) {
        ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
        image.increaseCursorSize();
        image.invalidate();
    }

    /**
     * Decrease the cursor size when button clicked
     * @param v
     */
    public void onDecreaseSizeClicked(View v) {
        ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
        image.decreaseCursorSize();
        image.invalidate();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            // recycle bitmaps
            ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
            if( m_imageSet ) {    
                image.recycleBitmaps();
            }
            // open gallery activity to choose image
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, IMAGE_PICK); 
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Post to xxxxx's wall yes/no listener
     */
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {            
            switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                // export and upload photos
                // get the five images to upload
                ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
                m_bitmaps = image.exportToImages();
                new FacebookUploadAndTagPhoto(1).execute();  
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                new FacebookUserLogoff().execute();
                break;
            }
        }
    };

    /**
     * Try restoring session for ease of banner posting
     */
    private void trySessionRestore() {
        // sets username and user id
        m_name = SessionStore.restoreName(this);
        m_id = SessionStore.restoreId(this);            

        // yes/no dialog to verify user wants to post the banner

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Post to " + m_name + "?").setPositiveButton("Yes", dialogClickListener)
        .setNegativeButton("No", dialogClickListener).show(); 
    }

    /**
     * Tries to login to Facebook with app dialog
     */
    private void tryFacebookLogin() {
        m_facebook.authorize(MakeBannerMemActivity.this, new String[] { AppConstants.JSON_PUBLISH_STREAM, AppConstants.JSON_PUBLISH_PHOTOS }, Facebook.FORCE_DIALOG_AUTH, new DialogListener() {

            public void onComplete(Bundle values) {

                // obtain user's full name and member identification number for posting photos
                try {
                    String response = m_facebook.request(AppConstants.JSON_ME);
                    JSONObject jsonObj;
                    try {
                        jsonObj = new JSONObject(response);
                        m_id = jsonObj.getString(AppConstants.JSON_ME_ID);
                        m_name = jsonObj.getString(AppConstants.JSON_ME_NAME);                                
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // save session for user and try posting the photos
                SessionStore.save(m_facebook, MakeBannerMemActivity.this, m_name, m_id);                
                trySessionRestore();  
            }

            /**
             * Print Facebook Error in Alert Dialog
             */
            public void onFacebookError(FacebookError error) {
                String errorMsg = error.toString();  
                AlertDialog alert = ActivityUtil.getAlertOkDialogue(MakeBannerMemActivity.this, errorMsg);
                alert.show();
            }    

            /**
             * Print Dialog Error in Alert Dialog            
             */
            public void onError(DialogError e) {
                String errorMsg = e.toString();
                AlertDialog alert = ActivityUtil.getAlertOkDialogue(MakeBannerMemActivity.this, errorMsg);
                alert.show();
            }    

            public void onCancel() {}

        });   
    }

    // upload and tag user in the 5 created photos
    public void onPostToFacebookClicked(View v) {

        // posting facebook banner (do not allow screen switch)
        m_isPostingBanner = true;

        try {
            // try to restore session
            if( SessionStore.restore(m_facebook, this) ) {
                trySessionRestore();
            }
            else {
                tryFacebookLogin();
            }
        	
        	// register the user clicked the button
            tracker.trackEvent(
            		"Button",  // Category
                    "Click",  // Action
                    "PostCustom", // Label
                    27);       // Value
        }
        // session restore can get funky with SSO.  If there is an error, then try restarting login
        catch( Exception e ) {
            tryFacebookLogin();
        }
    }

    // this is called when the screen rotates.
    // (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if( m_imageSet && !m_isPostingBanner ) {
            ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
            image.recycleBitmaps();
            image.setBitmap(this, m_filePath);
            image.invalidate();
        }
    }

    /**
     * Create options menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return ActivityUtil.createBannerMakerOptionsMenu(this, menu);
    }
    
    @Override
    protected void onDestroy() {
      super.onDestroy();
      // Stop the tracker when it is no longer needed.
      tracker.stopSession();
    }

    /**
     * Control flow for options menu selection
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
        if (item.getItemId() == R.id.menu_help) {
            ActivityUtil.loadHelpActivity(this);
        }
        else if (item.getItemId() == R.id.menu_home ) {
        	ActivityUtil.loadLoginActivity(this);
        }
        else if (item.getItemId() == R.id.menu_zoom) {
        	// zoom in image
        	ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);   
        	image.adjustZoomLevel(-.2f);
        }
        else if (item.getItemId() == R.id.menu_zoom_out) {
        	// zoom out image
        	ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);   
        	image.adjustZoomLevel(.2f);
        }
        return true;
    }  

    /**
     * Getter function to see if it is posting a banner
     * @return
     */
    public boolean isPostingBanner() {
        return m_isPostingBanner;
    }

    @Override
    public void finish() {
        ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
        if( m_imageSet ) {    
            image.recycleBitmaps();
        }
        super.finish();
    }

    /**
     * Tries to upload and tag photos
     */
    private class FacebookUploadAndTagPhoto extends AsyncTask<Void, String, Boolean> {

        private ProgressDialog progressDialogue = new ProgressDialog(MakeBannerMemActivity.this);
        private String errorMsg = null;
        private int photoNum;

        public FacebookUploadAndTagPhoto(int aPhotoNum) {
            super();
            photoNum = aPhotoNum;
        }

        /*
         * Display progress dialogue
         */
        @Override
        protected void onPreExecute() {            
            progressDialogue.setMessage("Uploading photo " + photoNum + " of 5...");
            progressDialogue.show();
        }

        /*
         * Try to upload and tag photo through facebook
         */
        @Override
        protected Boolean doInBackground(Void... param) {

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            m_bitmaps.get(photoNum-1).compress(Bitmap.CompressFormat.JPEG, 100, stream);                
            byte[] imageBytes = stream.toByteArray();

            // add all the information to send an upload and tag photo request
            Bundle params = new Bundle();                
            params.putString(Facebook.TOKEN, m_facebook.getAccessToken());                                         
            params.putByteArray(AppConstants.JSON_PICTURE, imageBytes);

            // add self tag
            JSONObject tags = new JSONObject();                
            try {
                tags.put(AppConstants.JSON_TAG_UID, m_id);
                tags.put(AppConstants.JSON_TAG_POSITION_X, 1);
                tags.put(AppConstants.JSON_TAG_POSITION_Y, 1);
            } catch (JSONException e) {
                errorMsg = e.toString();
            }
            JSONArray tagsArray = new JSONArray();
            tagsArray.put(tags);

            params.putString(AppConstants.JSON_TAGS, tagsArray.toString());

            String response = null;
            // try sending the request
            try {
                response = m_facebook.request(AppConstants.JSON_METHOD_UPLOAD_PHOTO, params, AppConstants.JSON_POST);
            } catch (FileNotFoundException e) {
                errorMsg = e.toString();
            } catch (MalformedURLException e) {
                errorMsg = e.toString();
            } catch (IOException e) {
                errorMsg = e.toString();
            }

            // recycle bitmap created
            m_bitmaps.get(photoNum-1).recycle();

            return Boolean.valueOf(errorMsg == null);
        }

        /**
         * Can use UI thread here.
         */
        @Override
        protected void onPostExecute(Boolean result) {

            if (progressDialogue.isShowing()) {
                progressDialogue.dismiss();
            }

            // Display error dialogue if you can't authenticate
            if (result.booleanValue() == false) {
                AlertDialog alert = ActivityUtil.getAlertOkDialogue(MakeBannerMemActivity.this, errorMsg);
                alert.show();
            } else {
                if( photoNum == 5 ) {

                    // recycle bitmaps to free up memory
                    ScrollableImageView image = (ScrollableImageView)findViewById(R.id.MemoryImage);
                    image.recycleBitmaps();
                    for(int i = 0; i < m_bitmaps.size(); i++) {
                        m_bitmaps.get(i).recycle();
                    }
                    m_bitmaps = null;
                    image = null;
                    System.gc();

                    AlertDialog alert = ActivityUtil.getAlertOkFinishDialogue(MakeBannerMemActivity.this, "Upload Successful!");
                    alert.show();
                }
                else {
                    new FacebookUploadAndTagPhoto(photoNum+1).execute(); 
                }
            }
        }
    }

    /**
     * Tries to logoff user
     */
    private class FacebookUserLogoff extends AsyncTask<Void, Void, Boolean> {

        private ProgressDialog progressDialogue = new ProgressDialog(MakeBannerMemActivity.this);
        private boolean status = false;
        private String errorMsg = null;

        public FacebookUserLogoff() {
            super();
        }

        /*
         * Display progress dialogue
         */
        @Override
        protected void onPreExecute() {
            progressDialogue.setMessage(MakeBannerMemActivity.this.getString(R.string.label_logging_off));
            progressDialogue.show();
        }

        /*
         * Try to logoff of current Facebook user
         */
        @Override
        protected Boolean doInBackground(Void... param) {
            // logout of Facebook user
            try {
                m_facebook.logout(MakeBannerMemActivity.this);
                status = true;
            } catch (MalformedURLException e) {
                errorMsg = e.toString();
            } catch (IOException e) {
                errorMsg = e.toString();
            }

            return Boolean.valueOf(status);
        }

        /**
         * Can use UI thread here.
         */
        @Override
        protected void onPostExecute(Boolean result) {

            m_isPostingBanner = false;

            if (progressDialogue.isShowing()) {
                progressDialogue.dismiss();
            }

            // Display error dialogue if you can't authenticate
            if (result.booleanValue() == false) {
                AlertDialog alert = ActivityUtil.getAlertOkDialogue(MakeBannerMemActivity.this, errorMsg);
                alert.show();
            } else {
                // clear the session            
                SessionStore.clear(MakeBannerMemActivity.this);
                tryFacebookLogin();
            }
        }
    }    
}